using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.Domain.LJC;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Task = B.S.XZYData.Domain.ZSHH.Task;
using B.S.XZYData.Domain.Inventory;

namespace B.S.XZYData.Infrastructure
{
    /// <summary>
    /// 数据库初始化服务
    /// </summary>
    public class DatabaseInitializer
    {
        private readonly MyDbContext _dbContext;

        public DatabaseInitializer(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public void Initialize()
        {
            try
            {
                Console.WriteLine("开始数据库初始化...");
                
                // 创建数据库（如果不存在）
                _dbContext.DbMaintenance.CreateDatabase();
                Console.WriteLine("数据库创建/连接成功！");
                
                // 创建表结构
                Console.WriteLine("开始创建表结构...");
                _dbContext.CodeFirst.SetStringDefaultLength(200)
                    .BackupTable()  // 备份现有数据
                    .InitTables(
                    // RBAC模块表
                    typeof(AccountModel),
                    typeof(RoleModel),
                    typeof(PermissionModel),
                    typeof(AccountRoleModel),
                    typeof(PermissionRoleModel),
                    // 赵士恒业务模块表
                    typeof(Process),
                    typeof(ProcessCollectionData),
                    typeof(AssemblyWorkOrder),
                    typeof(AssemblyWorkOrderProductDetail),
                    typeof(Domain.ZSHH.Task),
                    typeof(ProductionStatistics),
                    // 张诗晗业务模块表
                    typeof(Defective),
                    // typeof(ProcessProductionRecord), // 暂时注释，类不存在
                    typeof(WorkReport),
                    typeof(WorkReportDefectiveItem),
                    typeof(WorkflowDefinitionModel),
                    typeof(WorkflowInstanceModel),
                    typeof(AuditModel),
                    typeof(ProductionStatistics),
                    //徐紫阳业务模块
                    typeof(SalesOrder),
                    typeof(SalesOrderProduct),
                    typeof(Team),
                    typeof(TeamMember),
                    typeof(DefectiveItemDistribution),
                    typeof(PermissionRoleModel),
                    
                    // 李嘉诚业务模块表
                    typeof(RouteModel),
                    typeof(RouteStepModel),
                    typeof(WorkOrderModel),
                    typeof(WorkOrderProcessModel),
                    typeof(WorkOrderAssignModel),
                    typeof(WorkOrderReportModel),
                    typeof(PlanModel),
                    typeof(PlanItemModel),
                    typeof(ProductModel),
                    typeof(WorkOrderReportRelationModel),

                    // 樊煜婷业务模块表
                    typeof(Warehousingmodel),
                    typeof(BalanceModel),
                    typeof(DetailsModel),
                    typeof(InventoryListModel),
                    typeof(OutboundModel)
             
                );
                
                Console.WriteLine("表结构创建完成！");

               
                
                // 初始化测试数据
                Console.WriteLine("开始初始化测试数据...");
                var testDataInitializer = new TestDataInitializer(_dbContext);
                testDataInitializer.InitializeDefectiveItemDistributionData();
           
                
                // 检查数据状态
                Console.WriteLine("开始检查数据状态...");
            
               
                
                Console.WriteLine("数据库初始化完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败：{ex.Message}");
                Console.WriteLine($"错误详情：{ex}");
                throw;
            }
        }

        /// <summary>
        /// 初始化基础数据
        /// </summary>
        public void InitializeBaseData()
        {
            try
            {
                // 检查是否已有数据
                var accountCount = _dbContext.AccountModel.Count();
                if (accountCount > 0)
                {
                    Console.WriteLine("数据库中已有数据，跳过基础数据初始化");
                    return;
                }

                // 创建默认管理员账户
                var adminAccount = new AccountModel
                {
                    Id = 1,
                    Name = "admin",
                    Pwd = "123456", // 实际项目中应该加密
                    RealName = "系统管理员",
                    IsState = true,
                    CreateTime = DateTime.Now,
                    IsDeleted = false
                };

                // 创建默认角色
                var adminRole = new RoleModel
                {
                    Id = 1,
                    RoleName = "超级管理员",
                    IsState = true,
                    CreateTime = DateTime.Now,
                    IsDeleted = false
                };

                // 创建默认权限
                var systemPermission = new PermissionModel
                {
                    Id = 1,
                    PermissionName = "系统管理",
                    PermissionURL = "/system",
                    ParentId = 0,
                    Number = 1,
                    IsDeleted = false
                };

                // 插入数据
                _dbContext.Insertable(adminAccount).ExecuteCommand();
                _dbContext.Insertable(adminRole).ExecuteCommand();
                _dbContext.Insertable(systemPermission).ExecuteCommand();

                // 创建用户角色关联
                var accountRole = new AccountRoleModel
                {
                    Id = 1,
                    AccountId = 1,
                    RoleId = 1,
                    IsDeleted = false
                };

                // 创建角色权限关联
                var rolePermission = new PermissionRoleModel
                {
                    Id = 1,
                    RoleId = 1,
                    PermissionId = 1,
                    IsDeleted = false
                };

                _dbContext.Insertable(accountRole).ExecuteCommand();
                _dbContext.Insertable(rolePermission).ExecuteCommand();

                Console.WriteLine("基础数据初始化完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"基础数据初始化失败：{ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 初始化赵士恒业务模块基础数据
        /// </summary>
        public void InitializeZSHHBaseData()
        {
            try
            {
                // 检查是否已有数据
                var processCount = _dbContext.Process.Count();
                if (processCount > 0)
                {
                    Console.WriteLine("赵士恒业务模块中已有数据，跳过基础数据初始化");
                    return;
                }

                // 创建示例工序数据
                var processes = new List<Process>
                {
                    new Process
                    {
                        Id=1,
                        ProcessNumber = "P001",
                        RoutdId = 1, // ✅ 添加工艺外键，关联到工艺路线ID=1
                        ProcessName = "破洞1",
                        ReportingPermissions = "Admin测试,测试,超级管理员,所有人",
                        ReportingRatio = 4,
                        DefectiveItemList = "BL20220727152545354300003 | 胶件不良,BL20220",
                        TestField1 = "测试数据1",
                        TestField2 = "测试数据2",
                        Creator = "超级管理员",
                        Updator = "超级管理员",
                        CreatorDate = DateTime.Now,
                        UpdatorDate = DateTime.Now
                    },
                    new Process
                    {
                        Id=2,
                        ProcessNumber = "P002",
                        RoutdId = 1, // ✅ 添加工艺外键，关联到工艺路线ID=1
                        ProcessName = "焊接",
                        ReportingPermissions = "3368,3369",
                        ReportingRatio = 6,
                        DefectiveItemList = "BL20220727152530033500001 | 上色不均匀,BL202",
                        TestField1 = "测试数据3",
                        TestField2 = "测试数据4",
                        Creator = "超级管理员",
                        Updator = "超级管理员",
                        CreatorDate = DateTime.Now,
                        UpdatorDate = DateTime.Now
                    },
                    new Process
                    {
                        Id=3,
                        ProcessNumber = "P003",
                        RoutdId = 2, // ✅ 添加工艺外键，关联到工艺路线ID=2
                        ProcessName = "打磨",
                        ReportingPermissions = "超级管理员",
                        ReportingRatio = 1,
                        DefectiveItemList = "",
                        TestField1 = "测试数据5",
                        TestField2 = "测试数据6",
                        Creator = "超级管理员",
                        Updator = "超级管理员",
                        CreatorDate = DateTime.Now,
                        UpdatorDate = DateTime.Now
                    }
                };

                // 插入工序数据
                _dbContext.Insertable(processes).ExecuteCommand();

                // 创建示例装配工单数据
                var assemblyWorkOrder = new AssemblyWorkOrder
                {
                    Id = 1,
                    DocumentNumber = "AWO2025001",
                    WorkOrderCount = 5,
                    CompletedWorkOrderCount = 2,
                    DocumentProgress = 40.00m,
                    Remarks = "示例装配工单",
                    Creator = "超级管理员",
                    Updator = "超级管理员"
                };

                _dbContext.Insertable(assemblyWorkOrder).ExecuteCommand();

                // 创建示例任务数据
                var tasks = new List<Domain.ZSHH.Task>
                {
                    new Domain.ZSHH.Task
                    {
                        Id = 1,
                        ProcessId = 1,
                        ProcessNumber = "P001",
                        ProcessName = "破洞1",
                        ReportingPermissions = "Admin测试,测试,超级管理员,所有人",
                        ReportingRatio = 4,
                        DefectiveItemList = "BL20220727152545354300003 | 胶件不良,BL20220",
                        AllocationList = "",
                        PlannedStartTime = DateTime.Now.AddDays(-1),
                        PlannedEndTime = DateTime.Now.AddDays(2),
                        PlannedQuantity = 7,
                        GoodQuantity = 0,
                        DefectiveQuantity = 0,
                        ActualStartTime = DateTime.Now.AddDays(-1),
                        ActualEndTime = null,
                        Creator = "超级管理员",
                        Updator = "超级管理员"
                    },
                    new Task
                    {
                        Id = 2,
                        ProcessId = 2,
                        ProcessNumber = "P002",
                        ProcessName = "焊接",
                        ReportingPermissions = "3368,3369",
                        ReportingRatio = 6,
                        DefectiveItemList = "BL20220727152530033500001 | 上色不均匀,BL202",
                        AllocationList = "",
                        PlannedStartTime = DateTime.Now.AddDays(-2),
                        PlannedEndTime = DateTime.Now.AddDays(1),
                        PlannedQuantity = 6,
                        GoodQuantity = 0,
                        DefectiveQuantity = 0,
                        ActualStartTime = DateTime.Now.AddDays(-2),
                        ActualEndTime = null,
                        Creator = "超级管理员",
                        Updator = "超级管理员"
                    }
                };

                _dbContext.Insertable(tasks).ExecuteCommand();

                Console.WriteLine("赵士恒业务模块基础数据初始化完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"赵士恒业务模块基础数据初始化失败：{ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 初始化张诗晗业务模块基础数据
        /// </summary>
        public void InitializeZSHBaseData()
        {
            try
            {
                // 若已存在数据则跳过
                var defectiveCount = _dbContext.Defective.Count();
                if (defectiveCount > 0)
                {
                    Console.WriteLine("张诗晗业务模块中已有数据，跳过基础数据初始化");
                    return;
                }

                // 1) 不良品项主数据
                var defectives = new List<Defective>
                {
                    new Defective { DefectiveCode = "BL202508141521490001", DefectiveName = "焊接不完全", CreateTime = DateTime.Parse("2025-08-14T15:21:49"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL202212152037000001", DefectiveName = "测试", CreateTime = DateTime.Parse("2022-12-15T20:37:00"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "111", DefectiveName = "111", CreateTime = DateTime.Parse("2022-08-23T15:13:08"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "202208231513080001", DefectiveName = "涂料不均匀", CreateTime = DateTime.Parse("2022-08-23T15:13:08"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "202207281513080001", DefectiveName = "气压不良", CreateTime = DateTime.Parse("2022-07-28T15:13:08"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL20220727152545354300003", DefectiveName = "胶件不良", CreateTime = DateTime.Parse("2022-07-27T15:25:45"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL20220727152530033500001", DefectiveName = "上色不均匀", CreateTime = DateTime.Parse("2022-07-27T15:25:30"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL20220727152530033500002", DefectiveName = "尺寸偏差", CreateTime = DateTime.Parse("2022-07-27T15:25:30"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL20220727152530033500003", DefectiveName = "重量超重", CreateTime = DateTime.Parse("2022-07-27T15:25:30"), CreatorId = 1, IsDeleted = false },
                    new Defective { DefectiveCode = "BL20220727152530033500004", DefectiveName = "安装孔偏差", CreateTime = DateTime.Parse("2022-07-27T15:25:30"), CreatorId = 1, IsDeleted = false }
                };
                _dbContext.Insertable(defectives).ExecuteCommand();

                // 2) 不良品项汇总 (暂时注释，类不存在)
                /*var records = new List<ProcessProductionRecord>
                {
                    new ProcessProductionRecord
                    {
                        WorkOrderNo = "WO2025001",
                        ProductNo = "P1001",
                        ProductName = "样品A",
                        ProductSpec = "规格1",
                        ProcessNo = "PROC01",
                        ProcessName = "焊接",
                        Producer = "张三",
                        ProductionStartTime = DateTime.Now.AddHours(-4),
                        ProductionEndTime = DateTime.Now.AddHours(-1),
                        DefectiveItems = "BL001:1;BL002:0",
                        ProcessPlanQty = 12,
                        ReportQty = 11,
                        GoodQty = 10,
                        DefectiveQty = 1,
                        CreateTime = DateTime.Now,
                        CreatorId = 1,
                        IsDeleted = false
                    }
                };
                _dbContext.Insertable(records).ExecuteCommand();*/

                // 3) 报工主表 + 不良明细
                var workReport = new WorkReport
                {
                    WorkOrderCode = "WO2025001",
                    ProcessName = "焊接",
                    ProductCode = "P1001",
                    ProductNo = "P1001",
                    ProductName = "样品A",
                    ProductSpec = "规格1",
                    ReportQty = 11,
                    Producer = "张三",
                    Unit = "件",
                    GoodQty = 10,
                    DefectiveQty = 1,
                    ProcessStatus = ProcessStatusEnum.Completed,
                    ProcessProgress = "100%",
                    StartTime = DateTime.Now.AddHours(-4),
                    EndTime = DateTime.Now.AddHours(-1),
                    ReportHours = 3m,
                    ReportMinutes = 180,
                    StandardEfficiency = 4,
                    ActualEfficiency = 3.67m,
                    ComplianceRate = 91.67m,
                    PricingMethod = PricingMethodEnum.ByPiece,
                    WageUnitPrice = 10,
                    EstimatedWage = 110,
                    BonusAmount = 0,
                    PenaltyAmount = 0,
                    CreateTime = DateTime.Now,
                    CreatorId = 1,
                    IsDeleted = false
                };
                var reportId = _dbContext.Insertable(workReport).ExecuteReturnIdentity();

                var defectiveItems = new List<WorkReportDefectiveItem>
                {
                    new WorkReportDefectiveItem
                    {
                        WorkReportId = reportId,
                        DefectiveCode = "BL001",
                        DefectiveQty = 1,
                        CreateTime = DateTime.Now,
                        CreatorId = 1,
                        IsDeleted = false
                    }
                };
                _dbContext.Insertable(defectiveItems).ExecuteCommand();

                // 4) 流程模版定义
                var wfDef = new WorkflowDefinitionModel
                {
                    DefintionId = "DEF-001",
                    Version = 1,
                    Title = "报工审批流程",
                    StepNodes = @"[{""stepId"":""S1"",""stepName"":""提交""}]",
                    FormTemplate = "{}",
                    CreateTime = DateTime.Now,
                    CreatorId = 1,
                    IsDeleted = false
                };
                _dbContext.Insertable(wfDef).ExecuteCommand();

                // 5) 流程业务实例
                var wfIns = new WorkflowInstanceModel
                {
                    WorkOrderCode = "WO2025001",
                    WorkOrderNo = "WO2025001-01",
                    ProcessName = "焊接",
                    ProcessCode = "PROC01",
                    Title = "报工审批",
                    WorkflowId = "WF-001",
                    StepId = "S1",
                    StepName = "提交",
                    AuditUserId = "1",
                    AuditUserName = "管理员",
                    DefinitionId = "DEF-001",
                    Version = 1,
                    ApplicantUserName = "zhangsan",
                    FormData = "{}",
                    Status = "发起",
                    CompletedTime = null,
                    CreateTime = DateTime.Now,
                    CreatorId = 1,
                    IsDeleted = false
                };
                _dbContext.Insertable(wfIns).ExecuteCommand();

                // 6) 审批记录
                var audit = new AuditModel
                {
                    WorkflowId = wfIns.WorkflowId,
                    StepId = wfIns.StepId,
                    StepName = wfIns.StepName,
                    ExecutePointerId = "ptr-1",
                    AuditUserId = 1,
                    AuditUserName = "管理员",
                    Remark = "提交",
                    Status = true,
                    OperationType = "通过",
                    CreateTime = DateTime.Now,
                    CreatorId = 1,
                    IsDeleted = false
                };
                _dbContext.Insertable(audit).ExecuteCommand();

                Console.WriteLine("张诗晗业务模块基础数据初始化完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"张诗晗业务模块基础数据初始化失败：{ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 初始化李嘉诚业务模块基础数据
        /// </summary>
        public void InitializeLJCBaseData()
        {
            try
            {
                // 检查是否已有数据 - 检查多个表确保不重复初始化
                var productCount = _dbContext.ProductModel.Count();
                var routeCount = _dbContext.RouteModel.Count();
                var planCount = _dbContext.PlanModel.Count();
                
                if (productCount > 0 || routeCount > 0 || planCount > 0)
                {
                    Console.WriteLine("李嘉诚业务模块中已有数据，跳过基础数据初始化");
                    return;
                }

                // 1. 创建示例产品数据
                var products = new List<ProductModel>
                {
                    new ProductModel
                    {
                        Code = "PRD001",
                        Name = "智能手机外壳",
                        Spec = "规格A型",
                        Unit = "个",
                        Producer = "李师傅",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        ProductionStartTime = DateTime.Now.AddDays(-2),
                        ProductionEndTime = DateTime.Now.AddDays(-1)
                    },
                    new ProductModel
                    {
                        Code = "PRD002", 
                        Name = "平板电脑支架",
                        Spec = "标准型",
                        Unit = "套",
                        Producer = "王师傅",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        ProductionStartTime = DateTime.Now.AddDays(-1),
                        ProductionEndTime = DateTime.Now
                    },
                    new ProductModel
                    {
                        Code = "PRD003",
                        Name = "耳机转接头",
                        Spec = "Type-C",
                        Unit = "个",
                        Producer = "张师傅",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        ProductionStartTime = DateTime.Now,
                        ProductionEndTime = DateTime.Now.AddDays(1)
                    }
                };
                _dbContext.Insertable(products).ExecuteCommand();

                // 2. 创建工艺路线数据
                var routes = new List<RouteModel>
                {
                    new RouteModel
                    {
                        Code = "RT001",
                        Name = "手机外壳生产路线",
                        Approved = 1,
                        Remark = "标准手机外壳生产工艺",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    },
                    new RouteModel
                    {
                        Code = "RT002",
                        Name = "支架组装路线",
                        Approved = 1,
                        Remark = "平板支架组装工艺",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(routes).ExecuteCommand();

                // 3. 创建工艺路线工序数据
                var routeSteps = new List<RouteStepModel>
                {
                    // 手机外壳生产路线工序
                    new RouteStepModel
                    {
                        RouteId = 1,
                        Sequence = 1,
                        ProcessCode = "P001",
                        ProcessName = "注塑成型",
                        Ratio = 1.0m,
                        Type = "生产",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    },
                    new RouteStepModel
                    {
                        RouteId = 1,
                        Sequence = 2,
                        ProcessCode = "P002",
                        ProcessName = "表面处理",
                        Ratio = 0.8m,
                        Type = "生产",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    },
                    new RouteStepModel
                    {
                        RouteId = 1,
                        Sequence = 3,
                        ProcessCode = "P003",
                        ProcessName = "质量检验",
                        Ratio = 0.2m,
                        Type = "检验",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    },
                    // 支架组装路线工序
                    new RouteStepModel
                    {
                        RouteId = 2,
                        Sequence = 1,
                        ProcessCode = "P004",
                        ProcessName = "零件准备",
                        Ratio = 0.3m,
                        Type = "准备",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    },
                    new RouteStepModel
                    {
                        RouteId = 2,
                        Sequence = 2,
                        ProcessCode = "P005",
                        ProcessName = "组装",
                        Ratio = 1.0m,
                        Type = "生产",
                        CreateBy = "系统管理员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "系统管理员",
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(routeSteps).ExecuteCommand();

                // 4. 创建生产计划数据
                var plans = new List<PlanModel>
                {
                    new PlanModel
                    {
                        Code = "PLAN2025001",
                        Remark = "2025年第一季度生产计划",
                        CreateBy = "计划员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "计划员",
                        UpdateTime = DateTime.Now
                    },
                    new PlanModel
                    {
                        Code = "PLAN2025002",
                        Remark = "紧急订单生产计划",
                        CreateBy = "计划员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "计划员",
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(plans).ExecuteCommand();

                // 5. 创建生产计划明细数据
                var planItems = new List<PlanItemModel>
                {
                    new PlanItemModel
                    {
                        PlanId = 1,
                        ProductCode = "PRD001",
                        ProductName = "智能手机外壳",
                        Spec = "规格A型",
                        Quantity = 1000,
                        DoneQuantity = 200,
                        WorkOrderCode = "WO2025001",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new PlanItemModel
                    {
                        PlanId = 1,
                        ProductCode = "PRD002",
                        ProductName = "平板电脑支架",
                        Spec = "标准型",
                        Quantity = 500,
                        DoneQuantity = 100,
                        WorkOrderCode = "WO2025002",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new PlanItemModel
                    {
                        PlanId = 2,
                        ProductCode = "PRD003",
                        ProductName = "耳机转接头",
                        Spec = "Type-C",
                        Quantity = 2000,
                        DoneQuantity = 0,
                        WorkOrderCode = "WO2025003",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(planItems).ExecuteCommand();

                // 6. 创建工单数据
                var workOrders = new List<WorkOrderModel>
                {
                    new WorkOrderModel
                    {
                        Code = "WO2025001",
                        PlanItemId = 1,
                        RouteId = 1,
                        ProductCode = "PRD001",
                        ProductName = "智能手机外壳",
                        Spec = "规格A型",
                        Unit = "个",
                        PlannedQuantity = 1000,
                        ActualQuantity = 200,
                        GoodQuantity = 195,
                        BadQuantity = 5,
                        Status = "生产中",
                        PlannedStartTime = DateTime.Now.AddDays(-5),
                        PlannedEndTime = DateTime.Now.AddDays(5),
                        ActualStartTime = DateTime.Now.AddDays(-5),
                        ActualEndTime = null,
                        Remark = "第一批生产工单",
                        CreateBy = "计划员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "计划员",
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderModel
                    {
                        Code = "WO2025002",
                        PlanItemId = 2,
                        RouteId = 2,
                        ProductCode = "PRD002",
                        ProductName = "平板电脑支架",
                        Spec = "标准型",
                        Unit = "套",
                        PlannedQuantity = 500,
                        ActualQuantity = 100,
                        GoodQuantity = 98,
                        BadQuantity = 2,
                        Status = "生产中",
                        PlannedStartTime = DateTime.Now.AddDays(-3),
                        PlannedEndTime = DateTime.Now.AddDays(7),
                        ActualStartTime = DateTime.Now.AddDays(-3),
                        ActualEndTime = null,
                        Remark = "支架生产工单",
                        CreateBy = "计划员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "计划员",
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderModel
                    {
                        Code = "WO2025003",
                        PlanItemId = 3,
                        RouteId = 1,
                        ProductCode = "PRD003",
                        ProductName = "耳机转接头",
                        Spec = "Type-C",
                        Unit = "个",
                        PlannedQuantity = 2000,
                        ActualQuantity = 0,
                        GoodQuantity = 0,
                        BadQuantity = 0,
                        Status = "待开始",
                        PlannedStartTime = DateTime.Now.AddDays(1),
                        PlannedEndTime = DateTime.Now.AddDays(10),
                        ActualStartTime = null,
                        ActualEndTime = null,
                        Remark = "紧急订单",
                        CreateBy = "计划员",
                        CreateTime = DateTime.Now,
                        UpdateBy = "计划员",
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(workOrders).ExecuteCommand();

                // 7. 创建工单工序计划数据
                var workOrderProcesses = new List<WorkOrderProcessModel>
                {
                    // WO2025001 的工序
                    new WorkOrderProcessModel
                    {
                        WorkOrderId = 1,
                        Sequence = 1,
                        ProcessCode = "P001",
                        ProcessName = "注塑成型",
                        PlannedQuantity = 1000,
                        ReportedQuantity = 200,
                        GoodQuantity = 195,
                        BadQuantity = 5,
                        Ratio = 1.0m,
                        PlannedStartTime = DateTime.Now.AddDays(-5),
                        PlannedEndTime = DateTime.Now.AddDays(-3),
                        ActualStartTime = DateTime.Now.AddDays(-5),
                        ActualEndTime = null,
                        Status = "进行中",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderProcessModel
                    {
                        WorkOrderId = 1,
                        Sequence = 2,
                        ProcessCode = "P002",
                        ProcessName = "表面处理",
                        PlannedQuantity = 1000,
                        ReportedQuantity = 150,
                        GoodQuantity = 148,
                        BadQuantity = 2,
                        Ratio = 0.8m,
                        PlannedStartTime = DateTime.Now.AddDays(-3),
                        PlannedEndTime = DateTime.Now.AddDays(-1),
                        ActualStartTime = DateTime.Now.AddDays(-3),
                        ActualEndTime = null,
                        Status = "进行中",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    // WO2025002 的工序
                    new WorkOrderProcessModel
                    {
                        WorkOrderId = 2,
                        Sequence = 1,
                        ProcessCode = "P004",
                        ProcessName = "零件准备",
                        PlannedQuantity = 500,
                        ReportedQuantity = 100,
                        GoodQuantity = 100,
                        BadQuantity = 0,
                        Ratio = 0.3m,
                        PlannedStartTime = DateTime.Now.AddDays(-3),
                        PlannedEndTime = DateTime.Now.AddDays(-2),
                        ActualStartTime = DateTime.Now.AddDays(-3),
                        ActualEndTime = DateTime.Now.AddDays(-2),
                        Status = "已完成",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderProcessModel
                    {
                        WorkOrderId = 2,
                        Sequence = 2,
                        ProcessCode = "P005",
                        ProcessName = "组装",
                        PlannedQuantity = 500,
                        ReportedQuantity = 100,
                        GoodQuantity = 98,
                        BadQuantity = 2,
                        Ratio = 1.0m,
                        PlannedStartTime = DateTime.Now.AddDays(-2),
                        PlannedEndTime = DateTime.Now.AddDays(5),
                        ActualStartTime = DateTime.Now.AddDays(-2),
                        ActualEndTime = null,
                        Status = "进行中",
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(workOrderProcesses).ExecuteCommand();

                // 8. 创建工序分派数据
                var workOrderAssigns = new List<WorkOrderAssignModel>
                {
                    new WorkOrderAssignModel
                    {
                        WorkOrderProcessId = 1,
                        EmployeeId = 1001,
                        EmployeeName = "李师傅",
                        Quantity = 500,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderAssignModel
                    {
                        WorkOrderProcessId = 1,
                        EmployeeId = 1002,
                        EmployeeName = "王师傅",
                        Quantity = 500,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderAssignModel
                    {
                        WorkOrderProcessId = 2,
                        EmployeeId = 1003,
                        EmployeeName = "张师傅",
                        Quantity = 1000,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    },
                    new WorkOrderAssignModel
                    {
                        WorkOrderProcessId = 4,
                        EmployeeId = 1004,
                        EmployeeName = "赵师傅",
                        Quantity = 500,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    }
                };
                _dbContext.Insertable(workOrderAssigns).ExecuteCommand();

                // 9. 创建报工记录数据
                var workOrderReports = new List<WorkOrderReportModel>
                {
                    new WorkOrderReportModel
                    {
                        WorkOrderProcessId = 1,
                        RecordTime = DateTime.Now.AddDays(-4),
                        GoodQuantity = 95,
                        BadQuantity = 5,
                        DurationMinutes = 480,
                        Remark = "第一天生产报工",
                        UserId = 1001,
                        CreateTime = DateTime.Now.AddDays(-4)
                    },
                    new WorkOrderReportModel
                    {
                        WorkOrderProcessId = 1,
                        RecordTime = DateTime.Now.AddDays(-3),
                        GoodQuantity = 100,
                        BadQuantity = 0,
                        DurationMinutes = 480,
                        Remark = "第二天生产报工",
                        UserId = 1002,
                        CreateTime = DateTime.Now.AddDays(-3)
                    },
                    new WorkOrderReportModel
                    {
                        WorkOrderProcessId = 2,
                        RecordTime = DateTime.Now.AddDays(-2),
                        GoodQuantity = 148,
                        BadQuantity = 2,
                        DurationMinutes = 360,
                        Remark = "表面处理报工",
                        UserId = 1003,
                        CreateTime = DateTime.Now.AddDays(-2)
                    },
                    new WorkOrderReportModel
                    {
                        WorkOrderProcessId = 3,
                        RecordTime = DateTime.Now.AddDays(-2),
                        GoodQuantity = 100,
                        BadQuantity = 0,
                        DurationMinutes = 120,
                        Remark = "零件准备完成",
                        UserId = 1004,
                        CreateTime = DateTime.Now.AddDays(-2)
                    }
                };
                _dbContext.Insertable(workOrderReports).ExecuteCommand();

                Console.WriteLine("李嘉诚业务模块基础数据初始化完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"李嘉诚业务模块基础数据初始化失败：{ex.Message}");
                throw;
            }
        }
    }
}
